const redis = require("../../../../redis/init.js");
const schedule = require("node-schedule"); // 定时任务库
// 浏览量统计控制器
const ViewCountControl = async (req, res) => {
    try {
        // 仅统计每日浏览量
        const dailyViews = await redis.incr("dailyViewCount");
        // 返回成功消息
        res.send('设置成功');
    } catch (error) {
        console.error('Error in ViewCountControl:', error);
        res.status(500).send('内部服务器错误');
    }
}
// 定时任务：每天午夜清零每日浏览量并将其加到总浏览量
const resetDailyViewsAtMidnight = () => {
  schedule.scheduleJob("0 0 * * *", async () => {
    try {
      // 获取每日浏览量
      const dailyViews = await redis.get("dailyViewCount");
      // 更新总浏览量
      await redis.incrby("totalViewCount", parseInt(dailyViews));
      // 清零每日浏览量
      await redis.set("dailyViewCount", 0);
      console.log("Total views updated, and daily views reset at midnight.");
    } catch (error) {
      console.error("Error resetting daily views:", error);
    }
  });
};

// 启动定时任务
resetDailyViewsAtMidnight();
module.exports = ViewCountControl;
